
let bcrypt=require('bcryptjs')
let {JWT_SECRET}=require('../config/config.default.js')
let {getUser}=require('../server/user.js')

async  function userValitor(ctx,next){
   let {name,password}=ctx.request.body
   if(!name||!password){
       console.error('用户名或密码不能为空')
       ctx.app.emit('error',{
           code:'40000',
           message:'用户名或密码不能为空',
           result:''
       },ctx)
       return
   }
   await next()
}

async function userExist(ctx,next){
   let {name}=ctx.request.body

   try{
      let res=await getUser({name})

      if(res){
        console.error('用户名已经存在', {name })
        ctx.app.emit('error',{
            code:'40000',
            message:"用户已经存在",
            result:''
        },ctx)
        return
      }

   }catch(err){
      console.log('获取用户信息出错'+err)
      ctx.app.emit('error',{
        code:'50000',
        message:"获取用户信息出错",
        result:""
      },ctx)
      return
   }
   await next()
}

async function bcryptPassword(ctx,next){
   let {password}=ctx.request.body
   let salt=bcrypt.genSaltSync(10)
   let hash=bcrypt.hashSync(password,salt)
   ctx.request.body.password=hash
  await  next()
}

async function loginCheck(ctx,next){
   let {name,password}=ctx.request.body
   try{
      let res=await getUser({name})
      if(!res){
         ctx.app.emit('error',{
            code:'40000',
            message:"用户未注册",
            result:""
          },ctx)
          return 
      }
      if(!bcrypt.compareSync(password,res.password)){
         ctx.app.emit('error',{
            code:'40000',
            message:"密码错误",
            result:""
          },ctx)
          return
      }

   }catch(err){
      console.log('获取用户信息出错'+err)
      ctx.app.emit('error',{
        code:'50000',
        message:"获取用户信息出错",
        result:""
      },ctx)
      return
   }
   await next()
}
module.exports={
    userValitor,
    userExist,
    bcryptPassword,
    loginCheck
}